import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/video_controller_pool.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

import 'text_chat_item.dart';

class VideoChatItem extends StatefulWidget {
  final bool isTop;
  final String content;
  final dynamic actions;
  final ValueChanged<dynamic> onAction;

  const VideoChatItem(
      {Key key, this.isTop = false, this.content, this.actions, this.onAction})
      : super(key: key);

  @override
  _VideoChatItemState createState() => _VideoChatItemState();
}

class _VideoChatItemState extends State<VideoChatItem>
    with TickerProviderStateMixin {
  VideoPlayerController controller;
  AnimationController animationController;
  ValueNotifier<bool> isShow = ValueNotifier(true);
  Timer _timer;

  @override
  void initState() {
    super.initState();
    VideoControllerPool().obtainController(widget.content).then((value) {
      setState(() {
        controller = value;
      });
      controller.addListener(() {
        if (controller.value.isPlaying) {
          animationController.forward();
        } else {
          animationController.reverse();
        }
      });
    });
    animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 300));
  }

  @override
  void dispose() {
    VideoControllerPool().removeController(controller);
    animationController.dispose();
    super.dispose();
  }

  void onChangePlay() {
    bool isTapPlay = false;
    if (controller.value.isPlaying) {
      onPause();
    } else {
      isTapPlay = true;
      if (controller.value.position.inMilliseconds ==
          controller.value.duration.inMilliseconds) {
        controller.seekTo(Duration(milliseconds: 0));
      } else {
        onPlay();
      }
    }
    isShow.value = true;
    _timer?.cancel();
    if (isTapPlay == true)
      _timer = Timer(Duration(seconds: 1), () {
        isShow.value = false;
      });
  }

  void onPlay() async {
    await controller?.play();
  }

  void onPause() async {
    await controller?.pause();
  }

  @override
  Widget build(BuildContext context) {
    final style = TextChatItemStyle.of(context);
    List<Widget> actionWidgets = [];
    if (widget.actions != null && widget.actions is List) {
      for (var i = 0; i < widget.actions.length; i++) {
        final action = widget.actions[i];
        actionWidgets.add(PressedOpacityButton(
          onPressed: () {
            widget.onAction?.call(action);
          },
          padding: EdgeInsets.symmetric(
            vertical: getDp(10),
          ),
          child: Text(
            action['text'],
            style: TextStyle(
              color: aceBlueColor,
              fontSize: getSp(14),
              fontWeight: FontWeight.w400,
              height: 22 / 14,
            ),
          ),
        ));
      }
    }
    return Container(
      clipBehavior: Clip.antiAlias,
      margin: EdgeInsets.only(
          top: widget.isTop == false ? getDp(10) : 0.0, left: getDp(13)),
      constraints: BoxConstraints(
        maxWidth: getDp(249),
      ),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
        bottomRight:
            style?.archerAlign == Alignment.bottomRight && widget.isTop == true
                ? Radius.circular(0.0)
                : Radius.circular(16),
        bottomLeft: Radius.circular(16),
        topRight: Radius.circular(16),
        topLeft: style?.archerAlign == Alignment.topLeft && widget.isTop == true
            ? Radius.circular(0.0)
            : Radius.circular(16),
      )),
      child: Column(
        children: [
          controller == null
              ? Container()
              : Material(
                  color: Colors.black,
                  clipBehavior: Clip.antiAlias,
                  borderRadius: BorderRadius.circular(getDp(5)),
                  child: AspectRatio(
                      aspectRatio: controller.value.aspectRatio,
                      child: GestureDetector(
                        onTap: onChangePlay,
                        child: Stack(
                          children: [
                            VideoPlayer(controller),
                            Center(
                              child: _buildPlayButton(),
                            ),
                            Positioned(
                              bottom: 0,
                              left: 0,
                              right: 0,
                              child: ValueListenableBuilder(
                                  valueListenable: controller,
                                  builder: _buildProgress),
                            ),
                            // Positioned(
                            //   bottom: 0,
                            //   right: 0,
                            //   child: _buildFullScreen(),
                            // ),
                          ],
                        ),
                      )),
                ),
          ...actionWidgets,
        ],
      ),
    );
  }

  Widget _buildPlayButton() {
    return ValueListenableBuilder<bool>(
      valueListenable: isShow,
      builder: (BuildContext context, bool value, Widget child) =>
          Visibility(visible: value, child: child),
      child: AnimatedBuilder(
          animation: animationController, builder: _buildAnimatedWidget),
    );
  }

  Widget _buildAnimatedWidget(BuildContext context, Widget child) {
    return AnimatedIcon(
      size: getDp(46),
      icon: AnimatedIcons.play_pause,
      progress: animationController,
      color: Colors.white,
    );
  }

  Widget _buildProgress(
      BuildContext context, VideoPlayerValue value, Widget child) {
    return value.duration.inMilliseconds == 0
        ? Container()
        : LinearProgressIndicator(
            value: value.isBuffering
                ? null
                : value.position.inMilliseconds / value.duration.inMilliseconds,
            minHeight: getDp(2),
            color: value.isBuffering ? aceRedColor : aceBlueColor,
          );
  }

  Widget _buildFullScreen() {
    return IconButton(
      onPressed: () {},
      icon: Icon(
        Icons.fullscreen,
        size: getDp(32),
      ),
      color: Colors.white,
    );
  }
}
